package com.webserver.controller;

import com.webserver.http.HttpRequest;
import com.webserver.http.HttpResponse;
import com.webserver.vo.Article;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

/**
 * 处理文章相关业务
 */
public class ArticleController {
    //保存所有文章信息的目录的名字
    private static String articleDirName = "./articles/";

    static {
        //程序加载时判断一下保存所有用户信息的目录是否存在，不存在先自动创建出来
        File articleDir = new File(articleDirName);
        if(!articleDir.exists()){
            articleDir.mkdirs();
        }
    }



    public void writeArticle(HttpRequest request, HttpResponse response){
        System.out.println("处理发表文章...");
        String title = request.getParameter("title");
        String author = request.getParameter("author");
        String content = request.getParameter("content");

        if(title==null||author==null||content==null){
            response.setEntity(new File("./webapps/myweb/article_fail.html"));
            return;
        }
        try(
                ObjectOutputStream oos = new ObjectOutputStream(
                       new FileOutputStream(articleDirName+title+".obj")
                );
                ){
            Article article = new Article(title,content,author);
            oos.writeObject(article);
            //响应发表成功页面
            response.setEntity(new File("./webapps/myweb/article_success.html"));
        }catch(IOException e){
            e.printStackTrace();
        }


        System.out.println("发表文章处理完毕!");
    }
}
